package current_limiting

import (
	"sync"
	"time"
)

type Counter struct {
	rate  int           // 窗口内最多允许请求数
	begin time.Time     // 计数开始时间
	cycle time.Duration // 时间窗口
	count int           // 窗口内累计请求的次数
	lock  sync.Mutex    // 互斥锁，防止并发
}

func (l *Counter) NewLimit(r int, cycle time.Duration) {
	l.begin = time.Now()
	l.rate = r
	l.cycle = cycle
	l.count = 0
}

func (l *Counter) Reset(begin time.Time) {
	l.begin = begin
	l.count = 0
}
func (l *Counter) Allow() bool {
	if l.count >= l.rate-1 {
		now := time.Now()
		if now.Sub(l.begin) > l.cycle {
			l.Reset(now)
			return true
		} else {
			return false
		}
	} else {
		l.count++
		return true
	}
}
